package com.cn.medicalcare.controller.backstageservlet.superadmin;

import com.cn.medicalcare.customtool.JsonTool;
import com.cn.medicalcare.pojo.Admin;
import com.cn.medicalcare.service.AdminService;
import com.cn.medicalcare.service.serviceimpl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

@WebServlet("/backstage/superadmin/insertadmin.json")
public class AdminInsertServlet extends HttpServlet {

    private AdminService adminService = AdminServiceImpl.getInstance();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String role = req.getParameter("role");

        Map<String, Object> map = new LinkedHashMap<>();
        PrintWriter pw = resp.getWriter();
        try {
            int survival = Integer.valueOf(req.getParameter("survival"));
            if ((username != null && username.length() > 0) && (role != null && role.length() > 0)) {
                Admin admin = new Admin().setUsername(username).setRole(role).setSurvival(survival);
                if (adminService.insertAdmin(admin)) {
                    map.put("status", 200);
                } else {
                    map.put("status", 500);
                }
            }
        } catch (Exception e) {
            map.put("status", 400);
        }
        pw.print(JsonTool.toJson(map));
    }
}
